package com.lazyframework.commons.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * 基于jackson的JSON操作工具类
 *
 * @author maoning
 */
public class ObjectMappers {

    private static final ObjectMapper objectMapper;

    public static String write2JSON(Object obj) {
        try {
            return objectMapper.writer().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static <T> Map<String, T> read2Map(String content) {
        try {
            return objectMapper.readValue(content, new TypeReference<Map<String, T>>() {
            });
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static <T> Map<String, T> read2Map(InputStream src) {
        try {
            return objectMapper.readValue(src, new TypeReference<Map<String, T>>() {
            });
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static <T> T read(Object obj) {
        String jsonStr = write2JSON(obj);
        try {
            return objectMapper.readValue(jsonStr, new TypeReference<T>(){});
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }

    static {
        objectMapper = new ObjectMapper();
    }

}
